package wsz.user.service.impl;

import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import wsz.api.CodeService;
import wsz.api.UserService;
import wsz.pojo.Token;
import wsz.user.dao.UserDao;
import wsz.util.ConstantsUtils;

import java.util.List;

/**
 * @author wsz
 * @date 2021/12/27 12:45
 **/
@Service
public class UserServiceImpl implements UserService {

    @Reference
    private CodeService codeService;

    @Autowired
    private UserDao userDao;

    @Override
    public Token modify(Token token) {
        return userDao.save(token);
    }

    /**
     * 登录参数校验
     * @param email
     * @param password
     * @return
     */
    @Override
    public Token findByEmailAndPwd(String email, String password) {
        Token token = new Token();
        token.setEmail(email);
        token.setPassword(password);

        List<Token> tokenList = userDao.findAll(Example.of(token));
        return tokenList.isEmpty() ? null : tokenList.get(0);
    }

    @Override
    public Token findByToken(String token) {
        Token user = new Token();
        user.setToken(token);
        Example<Token> example = Example.of(user);
        return userDao.findOne(example).get();
    }

    /**
     * 注册
     * @param email
     * @param password
     * @param code
     * @return
     */
    @Override
    public int register(String email, String password, String code) {

        // 判断是否已注册
        boolean registered = isRegistered(email);
        if (registered) {
            return ConstantsUtils.STATUS_4;
        }

        // code微服务-校验验证码
        int validate = codeService.validate(email, code);
        if (ConstantsUtils.STATUS_0 != validate) {
            return validate;
        }

        // 校验通过-新增人员
        Token newToken = new Token();
        newToken.setEmail(email);
        newToken.setPassword(password);
        userDao.save(newToken);

        return ConstantsUtils.STATUS_0;
    }

    /**
     * 判断邮箱是否已注册过
     * @param email
     * @return
     */
    @Override
    public boolean isRegistered(String email) {
        Token token = new Token();
        token.setEmail(email);
        Example<Token> example = Example.of(token);
        List<Token> all = userDao.findAll(example);
        return all.size() > 0;
    }
}
